﻿app.controller('indexController', function ($rootScope,$scope, $modal, $log, $interval, $timeout, $element, tabService, dicSet,$filter) {
    // 病人信息
    function GetPatient(param) {
        dicSet.GetPatient(param).success(function (data, header, config, status) {
            //响应成功
            console.log(data)
            console.log(data.ResultData)
            $scope.lists = data.ResultData;
        }).error(function (data, header, config, status) {
            //处理响应失败
            angular.alert('操作失败！');
            $log.log(status);
        })
    }
    function GetPO() {
        dicSet.GetPatient(0).success(function (data, header, config, status) {
            //响应成功
            console.log(data)
            console.log(data.ResultData)
            if(data.ResultData==null){
                return
            }
            $scope.unLength = data.ResultData.length;
        }).error(function (data, header, config, status) {
            //处理响应失败
            angular.alert('操作失败！');
            $log.log(status);
        })
    }
   function getPT() {
       dicSet.GetPatient(1).success(function (data, header, config, status) {
           //响应成功
           console.log(data)
           console.log(data.ResultData)
           if(data.ResultData==null){
               return
           }
           $scope.orLength = data.ResultData.length;
       }).error(function (data, header, config, status) {
           //处理响应失败
           angular.alert('操作失败！');
           $log.log(status);
       })
   }

    GetPO()
    getPT()
    GetPatient(0)
    function orderStatuO() {
        return      $scope.threes=true,
                    $scope.twos=false,
                    $scope.ones=false
    }
    function orderStatuT() {
        return       $scope.threes=false,
                     $scope.twos=true,
                     $scope.ones=false
    }
    var orderStatu;
    $scope.unOrder=function () {
        GetPatient(0)
        orderStatu=0
    };
    $scope.Order=function () {
        GetPatient(1)
        orderStatu=1
    }
    function clearLeftList() {
        return     $scope.searchdata.patientid='',
        $scope.searchdata.PatName='',
        $scope.searchdata.GenderCode='',
        $scope.searchdata.ReservationFlag=0;
    }
    $scope.searchdata={}
    $scope.checkSure=-1
    $scope.PatientList=function ($index) {
        $scope.checkSure=$scope.checkSure==$index?-1:$index
    }

    $('.yue-ul').on('click','li',function (e) {
        // $scope.searchdata.patientid=e.currentTarget.children[3].innerText
        console.log($scope.searchdata.patientid)
        if($(this).hasClass('checked')){
            orderStatuO()
            clearLeftList()
            SearchExam($scope.searchdata);


        }else{
            if(orderStatu==0){
                orderStatuO()
                $scope.searchdata.ReservationFlag=0;
            }else if(orderStatu==1){
                orderStatuT()
                $scope.searchdata.ReservationFlag=1
            }
            $scope.searchdata.patientid=e.currentTarget.children[4].innerText
            $scope.searchdata.PatName=e.currentTarget.children[0].innerText
            $scope.searchdata.GenderCode=e.currentTarget.children[1].innerText
            console.log($scope.searchdata.GenderCode)

            SearchExam($scope.searchdata);
        }
    })
    // 左侧条件查询事件
    // $scope.PatientLists=function ($event) {
    //     console.log($event.currentTarget)
    //     $scope.searchdata.patientid=$event.currentTarget.children[4].innerText
    //     $scope.searchdata.PatName=$event.currentTarget.children[0].innerText
    //     $scope.searchdata.GenderCode=$event.currentTarget.children[1].innerText
    //     console.log($scope.searchdata.GenderCode)
    //     $scope.searchdata.ReservationFlag=0;
    //     SearchExam($scope.searchdata);
    // }
    var curSelectedDate=null;
    var groupIds=null;
    var curGroupId=0;
    var selectedItems=[];
    $rootScope.rightShow=true
    //初始化
    init();
    $rootScope.bodyClass='backNone'

    $scope.myTable = {};
    $scope.someClickHandler = function (row, info) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        selectTableRow(row, info);
    };
    var selectTableRow = function (row, info) {
        var selectedTab = tabService.getTabByMenuID();
        var curScope = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement").scope();
        var api = curScope.myTable.api();
        if (!row) {
            row = api.row(function (idx, data, node) {
                return data.SerialNo == curScope.dicDataTreeSelection.data.SerialNo ? true : false;
            }).nodes().to$();
        }
        if (!info) {
            api.row(function (idx, data, node) {
                if (data.SerialNo == curScope.dicDataTreeSelection.data.SerialNo) {
                    info = data;
                    return true;
                }
            });
        }
    };
    $scope.rowCallback = function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        angular.element(nRow).unbind('click');
        angular.element(nRow).bind('click', function () {
            $scope.someClickHandler(angular.element(nRow), aData);
        });
        return nRow;
    };

    $scope.columnDefs = [
        { 'data': null, targets:0,width:'30px',
            createdCell: function (nTd, sData, oData, iRow, iCol) {
                jQuery(nTd).html("<div class='adiv' name='adiv'><input type='checkbox' name='checkList' value='" + sData + "'></div>");
            },
        },
        {'data': "ExamStatusCode",targets:1,width:'30px'},
        {"data": "ExamNo","orderable": false ,targets:2,width:'60px'},
        {"data": "ExamCategoryName","orderable": false,targets:3,width:'60px'},
        {"data": "ExamItemName","orderable": false ,targets:4,width:'200px'},
        //{"data": "ReservationDate","orderable": false,targets:5,width:'60px'},
        {"data": "DiagCode","orderable": false,targets:5,width:'60px'},
        {"data": "ChargeCategoryName","orderable": false,targets:6,width:'30px'},
        {"data": "ReqDoctorName","orderable": false,targets:7,width:'60px'},
        {"data": "ReqDeptName","orderable": false,targets:8,width:'60px'},
        {"data": "ReqDatetime","orderable": false,targets:9,width:'60px'},
        {"data": "VisitTypeName","orderable": false,targets:10 ,width:'50px'},
        {"data": "ExamItemCode",targets:11,width:'30px'},
        {"data": "ExamItemProject",targets:12,width:'30px'},
        {"data": "ExamItemPart",targets:13,width:'30px'},
        {"data": "PatientId",targets:14,width:'30px'},
        {"data": "Name",targets:15,width:'30px'},
        {"data": "VisitNo",targets:16,width:'30px'},
        {"data": "Gender",targets:17,width:'30px'},
        {"data": "ReservationId",targets:18,width:'30px'},
        {"data": "SerialNo",targets:19,width:'30px'},
        {"data": "BirthDate",targets:20,width:'30px'},
        {"data": "ReservationFlag",targets:21,width:'30px'},

    ];

    $scope.dtOptions = {
        order: [[0, 'desc']],
        info: false,
        ordering: false,
        paging: false,
        processing: false,
        searching: false,
        scrollY: '150px',
        autoWidth: false,
        stateSave: true,
        stateDuration: 60 * 60 * 24,
        lengthMenu: [14, 50, 100],
        pagingType: 'full_numbers',
        search: {
            caseInsensitive: true,
            regex: true,
            smart: false
        },
        language: {
            url: 'vendor/jquery/datatables/Chinese.json'
        },
        drawCallback: function () {
            var selectedTab = tabService.getTabByMenuID();
            var contentElement = angular.element("#" + "myMenu" + selectedTab.id).find(".contentElement");
            // setAutoTableHeadClass(contentElement);

            if (this.api().column(0).nodes() == null) {
                return;
            }

            this.api().column(1).nodes().each(function (cell, i) {
                console.log(cell)
                console.log(i)
                cell.innerHTML = i + 1;
            });
        }
    };
    // var table = $('#table_dictsystem').DataTable()

    function empty() {
        return    $scope.foomeassage='',
                  $scope.fooTips='',
                  $scope.tipTime='',
                  $scope.tipHour=''
    }
    $scope.foomeassage=''
    //checkbox全选
    var footMeassges=[]
    var footMeassge=''
    var footMeassgess=''
    var ExamInfos=[]
    // var all={}
    var AllParam={}
    var num=[]
    var inf=[]
    var ReservationFlagArray=[]
    jQuery('.all').click(function () {
        $(this).toggleClass('selected');
        if (jQuery(this).hasClass("selected")) {
            $('#table_dictsystem tbody tr').addClass('selected')
            var len=$('#table_dictsystem tbody tr').length
          // 全部中只选中未预约的
            for(var i=0;i<len;i++){
                var m=$('#table_dictsystem tbody tr')[i]
                num.push(m.children[2].innerText)
                var xx=m.children[11].innerText.substring(0,m.children[11].innerText.length-1)
                var ReservationFlagtext=m.children[21].innerText
                ReservationFlagArray.push(ReservationFlagtext)
                for(var i=0;i<ReservationFlagArray.length;i++){
                    for(var j=1;j<ReservationFlagArray.length;j++){
                       if(ReservationFlagArray[i]=ReservationFlagArray[j]){
                           allStatu=2//只有已预约未预约中一种
                       }else{
                           allStatu=1//两种都有
                       }
                           }
                }
                console.log(ReservationFlagtext)

                console.log(xx)
                var x='['+xx+']'
                console.log(x)
                inf.push(x)
                console.log(num)
                // ExamInfos.push(All)
                console.log(ExamInfos)
                    var conT=m.children[3].innerText
                    var conF=m.children[4].innerText
                    var ss=m.children[11].innerText
                    console.log(ss)
                    footMeassge=conT+' '
                    console.log(footMeassge)
                    footMeassge+=conF
                    console.log(footMeassge)
                    footMeassges.push(footMeassge)
                    footMeassgess=footMeassges.join(',')
                    $scope.foomeassage=footMeassgess


            }
            console.log(num)
            console.log(inf)
            for(var j in num){
                all={ExamNo:num[j],ExamItemNos:inf[j]}
                ExamInfos.push(all)
            }
            AllParam.ExamInfos=ExamInfos
            AllParam.date=$filter('date')(new Date().getTime(), "yyyy-MM-dd")
            console.log(ExamInfos)
            dicSet.GetResource(AllParam).success(function (data, header, config, status) {
                angular.forEach(data.ResultData, function (time) {
                    time.Date=$filter('date')(new Date(Date.parse(time.Date)), "yyyy-MM-dd")
                });

                dateData=data.ResultData;
                RenderDateControl(dateData);
                console.log(data)
                if(ExamInfos.length>1){
                    if(allStatu==1){
                        $scope.status=6;//选中项目中包含已预约项目，不能再预约
                    }else if(allStatu==2&&$scope.twos==true){
                        $scope.status=5;//已预约的项目可以取消预约


                    }else if(allStatu==2&&$scope.threes==true){
                        $scope.status=3;//点击查询获取预约方案

                    }
                }else {
                    if (ExamInfos.length == 1&&$scope.twos==true) {
                        // if($scope.twos==true){
                            $scope.status=5;//已预约的项目可以取消预约
                        // }else if ($scope.threes==true) {
                        //     $scope.status = 0;//显示时间段号源
                        // } else {
                        //     $scope.status = 2;//没有可预约的时间段请选择其它日期
                        // }
                    }
                }
                // if(data.RespCode==255){
                //     $scope.status=2
                // }
            }).error(function (data, header, config, status) {
                //处理响应失败
                angular.alert('操作失败！');
                $log.log(status);
            });
            // console.log($('tr')[1].children[1].innerText)
        } else {
            jQuery("tr").removeClass('selected');
            empty()
            $scope.status=1
            dicSet.GetResource().success(function (data, header, config, status) {
                angular.forEach(data.ResultData, function (time) {
                    time.Date=$filter('date')(new Date(Date.parse(time.Date)), "yyyy-MM-dd")
                });

                dateData=data.ResultData;
                RenderDateControl(dateData);

            }).error(function (data, header, config, status) {
                //处理响应失败
                angular.alert('操作失败！');
                $log.log(status);
            });
        }


    });
    // var clientWidth = document.getElementById("ellipsis").clientWidth;
    // var scrollWidth = document.getElementById("ellipsis").scrollWidth;


    //选中项目缓存
    var listItem=[];

    //设置选中行和缓存
    var SetCheckItem=function(selected,examCodes){
        //选择项目
        if(selected){
            for(var i=0;i<examCodes.length;i++){
                listItem.push(examCodes[i]);
            }
        //取消项目选择
        }else{
            for(var i=0;i<examCodes.length;i++){
                removeByValue(listItem,examCodes[i])
            }
        }
    }
    //根据选中项目缓存，设置查询参数【获取所有号源总数接口的参数】

    var GetExamItemsStr=function(){
        var retlist=[];
        for(var i=0;i<listItem.length;i++){
            var isTrue=false;
            for(var j=0;j<retlist.length;j++){
                if(retlist[j]==listItem[i]){
                    isTrue=true;
                    break;
                }
            }
            if(isTrue==true){
                continue;
            }
            retlist.push(listItem[i]);
        }
        var liststr="[";
        for(var i=0;i<retlist.length;i++){
            if(i==retlist.length-1){
                liststr+="'"+retlist[i]+"'"
            }else{
                liststr+="'"+retlist+"',";
            }
        }
        liststr+="]";
        
        return liststr;
    }
    function GetExamInfoParam() {
        var param="ExamInfos:[";
        var index = 0;
        angular.forEach(selectedItems,function (selectedItem) {
            var examNo=selectedItem.ExamNo;
            var examItemsStr=GetExamItemNosStr(selectedItem.ExamItemNos);
            var str = "{ExamNo:'"+examNo+"',ExamItemNos:["+examItemsStr+"]}";
            if(index==selectedItems.length-1){
                param+=str
            }else{
                param+=str+","
            }
            index++;
        });
        param+="]";
        return param;
    }
    function GetCancelParams() {
        var param=[];
        angular.forEach(selectedItems,function (selectedItem) {
            var examNo=selectedItem.ExamNo;
            param.push(examNo);
        });
        return param;
    }
    // 【获取所有号源总数接口】
    function SetNumberDaysCount(){
        if(selectedItems.length<=0){
            RenderDateControl(null);
            return;
        }
        if(HaveNumberFlag()!=1){
            RenderDateControl(null);
            return;
        }
        //{ExamInfos:[{ExamNo:"121149",ExamItemNos:["D00000249"]},{ExamNo:"121150",ExamItemNos:["D00000249"]}],Date:'2017/5/5'}
        var param="{"+GetExamInfoParam()+"}";
        dicSet.GetResource(param).success(function (data, header, config, status) {
            var dateData=[];
            angular.forEach(data.ResultData, function (time) {
                time.Date=$filter('date')(new Date(Date.parse(time.Date)), "yyyy-MM-dd")
            });

            dateData=data.ResultData;
            RenderDateControl(dateData);
        }).error(function (data, header, config, status) {
            //处理响应失败
            angular.alert('操作失败！');
            $log.log(status);
        });
    }
    var submitParam={}
    //条件查询检查申请单
    function SearchExam(param){
        selectedItems=[];
        dicSet.GetExamsByParams(param).success(function (data, header, config, status) {
            console.log(data)
            if(data==null){
                $scope.dtData = null;
                return ;
            }
            if(data.ResultData==null){
                $scope.dtData = null;
                return ;
            }
            if(data.ResultData.length<=0){
                $scope.dtData = null;
                return ;
            }
            //响应成功
            var retExamsDatas=GetExamInfos(data.ResultData)
            $scope.dtData = retExamsDatas;
        }).error(function (data, header, config, status) {
            //处理响应失败
            angular.alert('操作失败！');
            $log.log(status);
        });
    }
    //获取时段号源
    function GetStageTimeNumber() {
        var param="";
        if(curGroupId!=null){
            param="{"+GetExamInfoParam()+",Date:\""+curSelectedDate+"\",GroupNo:"+curGroupId+"}";
        }else{
            param="{"+GetExamInfoParam()+",Date:\""+curSelectedDate+"\"}";
        }

        dicSet.GetDayResource(param).success(function (data,header,config,status) {
            if(data.ResultData==null){return;}
            SetStageTimeItem(data.ResultData.TimeStageCountModels);
            if(groupIds==null || groupIds.length<=0){
                groupIds=GetGroups(data.ResultData.TimeStageCountModels)
            }
            ChangeControllerStatus();
        });
    }
    //设置时段号源显示每行列数
    function SetStageTimeItem(models){
        console.log(models)
        $scope.timeStages=models;
        var len = models.length;
        if(len==3){
            len=4
        }else if(len==1){
            len=2
        }
        $scope.colunmNum=Math.floor(24/len)
    }
    //设置时段号源
    function SetStageTimeNumber(){
        if(curSelectedDate!=null){
            if(selectedItems.length<=0){
                $scope.timeStages=[];
                return;
            }
        }else{
            curSelectedDate=$filter('date')(new Date().getTime(), "yyyy-MM-dd");
            $scope.timeStages=[];
        }
        if(HaveNumberFlag()!=1){
            $scope.timeStages=[];
            return;
        }
        GetStageTimeNumber();
    }
    //修改页面状态
    function ChangeControllerStatus(status) {
        if(status){
            $scope.status=status;
            return;
        }
        if(selectedItems.length>1){
            if(HaveNumberFlag()==0){
                $scope.status=6;//选中项目中包含已预约项目，不能再预约
            }else if(HaveNumberFlag()==2){
                $scope.status=5;//已预约的项目可以取消预约
            }else{
                $scope.status=3;//点击查询获取预约方案
                if($scope.calculateResults.length>0){
                    $scope.status=4;//计算号源的结果
                }
            }
        }else {
            if (selectedItems.length == 1) {
                if(HaveNumberFlag()==2){
                    $scope.status=5;//已预约的项目可以取消预约
                }else if ($scope.timeStages.length > 0) {
                    $scope.status = 0;//显示时间段号源
                } else {
                    $scope.status = 2;//没有可预约的时间段请选择其它日期
                }
            } else {
                $scope.status = 1;//请选中未预约的申请单
            }
        }
    }
    function GroupNumber() {
        var param="";
        if($scope.isGroup==false){
            param="{"+GetExamInfoParam()+",Date:\""+curSelectedDate+"\"}";
            choosed=0;
        }else{
            if(curGroupId<=0){
                if(groupIds.length>0){
                    curGroupId=groupIds[0];
                }
            }
            param="{"+GetExamInfoParam()+",Date:\""+curSelectedDate+"\",GroupNo:"+curGroupId+"}";
        }
        dicSet.GetGroupResource(param).success(function (data,header,config,status) {
            console.log(data)
            if(data.ResultData==null){return;}
            SetStageTimeItem(data.ResultData.TimeStageCountModels);
        })
    }
    function sortNumber(a,b)
    {
        return a - b
    }
    function GetGroups(numbers) {
        var groups=[];
        for(var i=0;i<numbers.length;i++){
            var isTrue=false;
            for(var j=0;j<groups.length;j++){
                if(groups[j]==numbers[i].GroupId){
                    isTrue=true;
                    break;
                }
            }
            if(isTrue){
                continue;
            }
            groups.push(numbers[i].GroupId);
        }
        groups.sort(sortNumber);
        return groups;
    }
    function GetCurGroupId(index) {
        for(var i=0;i<groupIds.length;i++){
            if(i==index){
                return groupIds[i];
            }
        }
        return null;
    }

    function ClearStageTimeItem(){
        $scope.timeStages=[];
    }

    //初始化方法
    function init() {
        $scope.choosed=-1;
        $scope.choose=function ($index) {
            $scope.choosed=$scope.choosed!=$index?$index:-1;
            curGroupId=GetCurGroupId($index);
            SetStageTimeNumber();
            ChangeControllerStatus();
        };
        // 日历框消失
        $scope.closeLB=function () {
            $('.data-left').find('ul').css('display','none');
            $('.date-birthday').find('ul').css('display','none');
            $('.data-right').find('ul').css('display',' block');
        };
        $scope.closeRB=function () {
            $('.data-right').find('ul').css('display','none');
            $('.date-birthday').find('ul').css('display','none');
            $('.data-left').find('ul').css('display',' block');
        };
        $scope.closeLR=function () {
            $('.data-left').find('ul').css('display','none');
            $('.data-right').find('ul').css('display','none');
            $('.date-birthday').find('ul').css('display',' block');
            // alert('..')
        };
        // 参数设置----------------------------------------------------------------开始

        // 性别选中
        $scope.selectgg=function () {
            $scope.searchdata.GenderCode=1
        };
        $scope.selectmm=function () {
            $scope.searchdata.GenderCode=2
        };
        // 条件查询
        $scope.searchdata= {};
        // 全部选项默认选中
        $scope.threes=true;
        $scope.searchdata.ReservationFlag=0;

        // 预约状态
        $scope.unorder=function () {
            $scope.searchdata.ReservationFlag=0;
            SearchExam($scope.searchdata);
            SetNumberDaysCount();
            ChangeControllerStatus();
        };
        $scope.order=function () {
            $scope.searchdata.ReservationFlag=1;
            SearchExam($scope.searchdata);
            SetNumberDaysCount();
            ChangeControllerStatus();
        };
        $scope.all=function () {
            delete $scope.searchdata.ReservationFlag;
            SearchExam($scope.searchdata);
            SetNumberDaysCount();
            ChangeControllerStatus();
        };
        $scope.search=function(){
            SearchExam($scope.searchdata);
            SetNumberDaysCount();
            ChangeControllerStatus();
        };
        SearchExam($scope.searchdata);
        //'{"ExamItemNos":["DFS00162"],"Date":"2017/3/27","GroupNo":"1"}'
        //获取某天分组
        $scope.showGroups=function(){
            if($scope.isGroup){
                $scope.fenzus=[];
                $scope.isGroup=false;
            }else{
                if(groupIds instanceof Array&&groupIds.length<=0){
                    $scope.fenzus = [];
                    $scope.isGroup=false;
                }else if(groupIds==null){
                    $scope.isGroup=false;
                }else{
                    $scope.fenzus = groupIds;
                    $scope.isGroup=true;
                }
            }
            // GroupNumber(param);
        };
        $scope.timeStages=[];
        $scope.isGroup=false;
        ChangeControllerStatus();
    }
    // 数组去除
    function removeByValue(arr, val) {
        for(var i=0; i<arr.length; i++) {
            if(arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
    }
    function RenderDateControl(dateData){
        $('#paginator-start-end').data('plugin_datepaginator').options.customData=dateData;
        if($scope.status==3){
            $('#paginator-start-end').data('plugin_datepaginator').options.onlyCustomData=true;
        }else{
            $('#paginator-start-end').data('plugin_datepaginator').options.onlyCustomData=false;
        }
        $('#paginator-start-end').data('plugin_datepaginator')._render();
    }
    function GetExamInfos(data){
        var retExamDatas=[];
        angular.forEach(data,function(resource){
            var retExamData = {};
            retExamData.SerialNo = resource.SerialNo;
            retExamData.ExamNo = resource.ExamNo;
            retExamData.ExamCategoryName = resource.ExamCategoryName;
            //retExamData.ReservationDate = resource.ReservationDate;
            retExamData.DiagCode = resource.DiagCode;
            retExamData.ChargeCategoryName = resource.ChargeCategoryName;
            retExamData.ReqDoctorName = resource.ReqDoctorName;
            retExamData.ReqDeptName = resource.ReqDeptName;
            retExamData.ReqDatetime = $filter('date')(resource.ReqDatetime, "yyyy-MM-dd hh:mm");
            retExamData.VisitTypeName = resource.VisitTypeName;
            retExamData.ExamItemName = "";
            retExamData.ExamItemCode = "";
            retExamData.ExamItemProject="";
            retExamData.ExamItemPart=resource.DiagCode;
            retExamData.ExamStatusCode=resource.ExamStatusCode
            retExamData.PatientId=resource.PatientId;
            retExamData.Name=resource.PatName;
            retExamData.VisitNo=resource.VisitNo;
            retExamData.Gender=resource.GenderCode;
            retExamData.ReservationId=resource.PatientId;
            retExamData.SerialNo=resource.SerialNo;
            retExamData.BirthDate=resource.BirthDate;
            retExamData.ReservationFlag=resource.ReservationFlag;
            
            // retExamData.ExamSubCategoryName="";
            var examDetailsData = resource.ExamDetails;
            angular.forEach(resource.ExamDetails,function (re) {
                retExamData.ExamItemProject=re.ExamItemName;
                retExamData.ExamItemName +=re.ExamItemName;
                if(re.ExamSubCategoryName!=null && re.ExamSubCategoryName!=""){
                    retExamData.ExamItemName +="["+re.ExamSubCategoryName+"] ";
                }
                retExamData.ExamItemCode +=re.ExamItemCode+",";
            });
            retExamDatas.push(retExamData);
        });
        return retExamDatas;
    }
    function SetSelectedItem(row){
        var examItem={};
        examItem.PatientId=row.currentTarget.children[14].innerText
        examItem.Name=row.currentTarget.children[15].innerText
        examItem.VisitNo=row.currentTarget.children[16].innerText
        examItem.Gender=row.currentTarget.children[17].innerText
        examItem.ReservationId=row.currentTarget.children[18].innerText
        examItem.SerialNo=row.currentTarget.children[19].innerText
        examItem.DateOfBirth=row.currentTarget.children[20].innerText
        examItem.ExamNo=row.currentTarget.children[2].innerText
        examItem.ExamReqDatetime=row.currentTarget.children[9].innerText
        examItem.ExamCategoryName=row.currentTarget.children[3].innerText
        examItem.ExamItemName=row.currentTarget.children[4].innerText
        examItem.ReservationFlag=row.currentTarget.children[21].innerText
        console.log(examItem.ReservationTime)
        var data=$filter('date')(new Date().getTime(), "yyyy-MM-dd");
        examItem.ReservationDate=data
        var examCode = row.currentTarget.children[11].innerText.substring(0,row.currentTarget.children[11].innerText.length-1);
        examItem.ExamItemNos=GetExamItemNos(examCode);
        return examItem;
    }

    function SetSelectedItems(examNo,row) {
        var isTrue=false;
        for(var i=0;i<selectedItems.length;i++) {
            if(selectedItems[i].ExamNo==examNo){
                removeByValue(selectedItems,selectedItems[i]);
                isTrue=true;
                return;
            }
        }
        if(isTrue==false){
            var selectedItem = SetSelectedItem(row);
            selectedItems.push(selectedItem);
        }
    }
    function GetSelectedItem(examNo) {
        for(var i=0;i<selectedItems.length;i++) {
            if(selectedItems[i].ExamNo==examNo){
                return selectedItems[i]
            }
        }
        return null;
    }
    function GetExamItemNos(examItemNosStr) {
        var itemNos=examItemNosStr.split(",");
        return itemNos;
    }
    function GetExamItemNosStr(examItemNos) {
        var index=0;
        var examItemNosStr="";
        angular.forEach(examItemNos,function (itemNo) {
            if(index==examItemNos.length-1){
                examItemNosStr+="'"+itemNo+"'";
            }else {
                examItemNosStr+="'"+itemNo+"',";
            }
        })
        return examItemNosStr;
    }
    //时间格式化

    var formatDate = function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? '0' + m : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + '年' + m + '月' + d+'日';
    };
    var currentDate=formatDate(new Date());
    var footMeassage=[];
    // var param={ExamInfos:[{ExamNo:"121149",ExamItemNos:["D00000249"]},{ExamNo:"121150",ExamItemNos:["D00000249"]}],Date:'2017/5/5'}

    $('table').on('click','tr',function (e) {
        //if($scope.twos!=true&&e.currentTarget.children[5].innerText==''){
        $(this).toggleClass('selected');
        $scope.calculateResults=[];
        var examNo=e.currentTarget.children[2].innerText;
        //设置选中行到缓存
        SetSelectedItems(examNo,e);
        //获取每天的号源总数
        SetNumberDaysCount();
        //设置时段号源
        SetStageTimeNumber();
        SetFootText($(this).hasClass('selected'),e.currentTarget.children[3].innerText,e.currentTarget.children[4].innerText);
        ChangeControllerStatus();
        //if($scope.twos==true){
        //    $(this).toggleClass('selected');
        //    if ($(this).hasClass('selected')) {
        
        //    }
        //}
        // var thisTip=e.currentTarget.children[3].innerText
        // thisTip+=e.currentTarget.children[4].innerText
        if($(this).hasClass('selected')){

            // footMeassges.push(thisTip)
        }else{
            // removeByValue(footMeassges,thisTip)
        }
    });
    function SetFootText(selected,examCategoryName,examItemName){
        if(selected==null){
            var dd= Date.parse(curSelectedDate);
            $scope.tipTime=footMeassage.length==0? "": formatDate(new Date(dd))
            return;
        }
        if(selected){
            footMeassage.push(examCategoryName+" "+examItemName);
            var dd= Date.parse(curSelectedDate);
            $scope.tipTime=formatDate(new Date(dd))
            $scope.fooTips = footMeassage.join(',').replace(new RegExp(',', 'g'), ' ');
        }else{
            removeByValue(footMeassage, examCategoryName+" "+examItemName);
            $scope.fooTips = footMeassage.join(',').replace(new RegExp(',', 'g'), ' ');
            if(footMeassage.length==0){
                $scope.tipTime=""
            }
        }
    }
    function HaveOverNumber(){
        for(var i=0;i<selectedItems.length;i++){
            if(selectedItems[i].ReservationFlag=="1"){
                return true;
            }
        }
        return false;
    }
    function HaveNumberFlag(){
        var flag=0;
        var reservationFlags=[];
        for(var i=0;i<selectedItems.length;i++){
            var isTrue=false;
            for(var j=0;j<reservationFlags.length;j++){
                if(reservationFlags[j]==selectedItems[i].ReservationFlag){
                    isTrue=true;
                    break;
                }
            }
            if(isTrue==false){
                reservationFlags.push(selectedItems[i].ReservationFlag);
            }
        }
        if(reservationFlags.length>1){
            flag=0;//两者都有
        }
        if(reservationFlags.length==1){
            if(reservationFlags[0]=="0"){
                flag=1;//只有未预约
            }else{
                flag=2;//只有已预约
            }
        }
        return flag;
    }

    $('.rili').on('click','.dp-item',function (e) {
        curGroupId = 0;
    });
    $scope.statuTime=true
    $('.fenzu-ul').on('click','div.change',function (e) {
        if(selectedItems.length<=0){
            return;
        }
        var examItem=selectedItems[0];
        examItem.GroupId=$(this).find('.groupId-span')[0].innerText
        examItem.ReservationTime=$(this).find('.time-span')[0].innerText


        if($(this).parent().hasClass('selecte')){
            $scope.tipHour='';
            examItem.ReservationTime=''
        }else{
            $scope.tipHour=$(this).find('.time-span')[0].innerText

        }
        if(examItem.ReservationTime!=''){
            $scope.statuTime=false
        }else{
            $scope.statuTime=true
        }
        curGroupId=examItem.GroupId;
    });

    // 监听input框
    $scope.$watch('searchdata.patientid',function (newvalue,oldvalue) {
        if(newvalue!=oldvalue&&newvalue.length>0){
            console.log(newvalue.length);
            $scope.loset=true
        }else{
            $scope.loset=false
        }
    });
    $scope.$watch('searchdata.ExamNo',function (newvalue,oldvalue) {
        if(newvalue!=oldvalue&&newvalue.length>0){
            // console.log(newvalue.length)
            $scope.loseo=true
        }else{
            $scope.loseo=false
        }
    });
    var h=$(window).height()-420;
    setTimeout(function () {
        $('#divs').height(h+'px')
    },10);
    // 时间块适应
    $scope.selecte=-1;
    $scope.selected=function ($index) {
        // console.log($event.target)
        if($scope.selecte!=$index){
            $scope.selecte=$index
        }else{
            $scope.selecte=-1;
        }
    };

    $scope.selectes=function () {
        $scope.isActive=true;
    };
    var dates=new Date();
    var data=$filter('date')(new Date().getTime(), "yyyy-MM-dd");

    var date=new Date(dates.getTime() - 24*60*60*1000*150);
    var sdate=$filter('date')(date, "yyyy-MM-dd");

    console.log(sdate);
    function setDate(data) {
      jQuery(function() {
        var options = {
            selectedDate: data,
            showOffDays: false,
            showStartOfWeek:false,
            itemWidth: 105,
            startDate:sdate,endDate:'2017-11-7',
            language: 'cn',
            text:'MM-DD ddd<br/>',
            textSelected:'MM-DD ddd<br/>',
            onSetCustomData:function(event,item,data){
                item.prefixText="<b style='color:#FF7D0C;position: relative;bottom: 2px'>"+data+"</b><b style='color:#FF7D0C;position: relative;bottom: 2px'>个</b>";
            },
            onSelectedDateChanged: function(event, date) {
                if(selectedItems.length<=0){
                    return;
                }
                var examItem= selectedItems[0];
                if(examItem.ReservationFlag!="1"){
                    examItem.ReservationDate=date._i
                }
                
                curSelectedDate=date._i;
                //发送请求
                if(date._i=='undefined'){
                    var d=new Date().getTime()
                    var data=$filter('date')(d, "yyyy-MM-dd");
                    console.log(data)
                    date._i=data
                }
                
                SetStageTimeNumber();
                SetFootText();
                $scope.calculateResults=[];
                $scope.isGroup=false;
                groupIds=[];
                ChangeControllerStatus();
            }
        };
        $('#paginator-start-end').datepaginator(options);

    })
    };
    setDate(data)
    // var param=[{'Groupid':'1','Patientid':'1','VisitNo':'1','Name':'a','Gender':'1','DateOfBirth':'2017-04-13T00:00:00',
    //     'ExamReqDatetime':'0001-01-T00:00:00'
    //     ,'Reservationid':'1','GrouName':'1','ReservationDate':'2017-04-14T00:00:00','ReservationTime':'1','ExamNo':'1','WeekName':'1',
    //     'CreateDatetime':'2017-04-14T00:00:00','CreaterCode':'1','Creater':'1','SerialNo':'120',ExamItemNos:['',]}];
    $scope.dis=true
    $scope.diss=false
    $scope.calculate=true
    $scope.calculates=false
    $scope.submits=function () {
        if(selectedItems.length<=0){
            return;
        }

        angular.alert('确定预约吗？', null, true).ok(function () {
            dicSet.submit(selectedItems).success(function (data, header, config, status) {
                curSelectedDate=$filter('date')(new Date().getTime(), "yyyy-MM-dd")
                angular.alert('预约成功！');
                // $scope.fooTips='';
                // $scope.tipTime='';
                // $scope.tipHour='';
                clearLeftList()
                SearchExam($scope.searchdata);
                orderStatuO()
                empty()
                setDate();
                SetNumberDaysCount();
                ChangeControllerStatus();
                GetPO()
                getPT()
                GetPatient(0)
                $scope.checkSure=-1
                $scope.statuTime=true

            }).error(function (data, header, config, status) {
                //处理响应失败
                angular.alert('预约失败！');
                $log.log(status);
            });
        }).cancel(function () { })

    }

    $scope.checkall=1
    console.log($scope.checkall)
    $scope.calculateResource=function () {
        // var param={ExamInfos:[{ExamNo:"121149",ExamItemNos:["D00000249"]},{ExamNo:"121150",ExamItemNos:["D00000249"]}],Date:'2017/5/5'}
        if($scope.checkall==0){
            var param="{"+GetExamInfoParam()+",Date:'"+curSelectedDate+"'}";
        }else if($scope.checkall==1){
            param=AllParam
        }

        dicSet.calculateResource(param).success(function (data,header,config,status) {
            // if(data.ResultData==null){return;}
            if(data.RespCode==404003){
                angular.alert('没有可预约的号源')
            }
            var calculateResults=[];
            angular.forEach(data.ResultData,function (data) {
                var selectedItem = GetSelectedItem(data.ExamNo);
                selectedItem.ReservationTime=data.TimeName;
                selectedItem.ReservationDate=curSelectedDate;

                var calculateResult={};
                calculateResult.ExamNo=selectedItem.ExamNo
                calculateResult.ReservationDate=curSelectedDate;
                calculateResult.ExamItemName=selectedItem.ExamItemName;
                calculateResult.ExamCategoryName=selectedItem.ExamCategoryName;
                calculateResult.ReservationTime=data.TimeName;
                calculateResults.push(calculateResult);
            });
            $scope.calculateResults=calculateResults;
            ChangeControllerStatus();
        });
    }
    $scope.cancel=function () {
        // alert('...')
        var param=GetCancelParams();
        angular.alert('确定取消吗？', null, true).ok(function () {
            dicSet.cancel(param).success(function (data, header, config, status) {
                console.log(data)
                if(data.RespCode!=0){ return angular.alert('取消失败！');}

                else{
                    curSelectedDate=$filter('date')(new Date().getTime(), "yyyy-MM-dd")
                    angular.alert('取消成功！');
                }
                // $scope.fooTips='';
                // $scope.tipTime='';
                // $scope.tipHour='';
                clearLeftList()
                SearchExam($scope.searchdata);
                orderStatuO()
                empty()
                setDate();
                SetNumberDaysCount();
                ChangeControllerStatus();
                GetPO()
                getPT()
                GetPatient(0)
                orderStatu=0
                $scope.checkSure=-1
                $scope.change=false
                $scope.changes=false

            }).error(function (data, header, config, status) {
                //处理响应失败
                angular.alert('取消失败！');
                $log.log(status);
            });
        }).cancel(function () { })
    }
});